//
//  M_OrderDetail.swift
//  letuofu
//
//  Created by dooland2 on 2020/6/9.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_OrderDetail: BaseViewControllerWithHeader,UITableViewDataSource,UITableViewDelegate {
    var tableView = UITableView(frame: CGRect.zero, style: .grouped)
    let addressView = UIView()
    let btmtoolView = UIView()
    var orderDic = [String:Any?]()
    let footView = M_OrderDetailFootView()
    let paybtn = Button()
    let seebtn = Button()
    let cancelbtn = Button()
    let signbtn = Button()
    
    var backCount = 2

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupHeadUI()
        setupUI()
    }
    
    
    override func _onBackButtonClick() {
        self.popViewController(vCount: backCount)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    //确认收货操作
        func signOrderAction(orderID: String, callback: @escaping () -> Void) {
            MBProgressHUD.showOrIncrease()
            let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                        "orderID":orderID]
            API.request(url: .M_OrderConfirmReceipt, params: params) { (result) in
                MBProgressHUD.hideOrDecrease()
                if result.success {
                    callback()
                }
                else {
                    let popup = PopupSureBox(title:"获取订单失败", sureText: "确定")
                    popup.show(vc: UIViewController.topMostController() ?? self)
                    popup.onSureButtonClick = {
                        //确定执行
                    }
                }
            }
        }
        
        
        //取消订单操作
        func cancelOrderAction(orderID: String, callback: @escaping () -> Void) {
            MBProgressHUD.showOrIncrease()
            let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                        "orderID":orderID]
            API.request(url: .M_CancelOrder, params: params) { (result) in
                MBProgressHUD.hideOrDecrease()
                if result.success {
                    callback()
                    UIViewController.topMostController()?.view.makeToast("取消订单成功", duration: 2.0, position: .center)

                }
                else {
                    UIViewController.topMostController()?.view.makeToast("取消订单失败", duration: 2.0, position: .center)

                }
            }
            
        }
        
    //刷新订单
        func getorderDetail(orderID: String, callback: @escaping ([String:Any?]) -> Void) {
            MBProgressHUD.showOrIncrease()
            let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                        "orderID":orderID]
            API.request(url: .M_GetUserOrderDetail, params: params) { (result) in
                MBProgressHUD.hideOrDecrease()
                if result.success {
                    if let data = result.data?.getDictionary("data") {
                        callback(data)
                    }
                }
                else {
                    let popup = PopupSureBox(title:"获取订单失败", sureText: "确定")
                    popup.show(vc: UIViewController.topMostController() ?? self)
                    popup.onSureButtonClick = {
                        //确定执行
                    }
                }
            }
            
        }
}

// MARK: UI
extension M_OrderDetail {
    func setupHeadUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "订单详情"
        drawRightButton(imageName: "xiangqingkefu_82")
        .addTarget(self, action: #selector(_kefuButtonClick(button:)), for: .touchUpInside)
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        
    }
    func setupUI() {
        
        let btm = 50
        ///底部工具条部分
        safeView.drawView(view: btmtoolView) { (make) in
            make.bottom.equalToSuperview().offset(btm)
            make.left.right.equalToSuperview()
            make.height.equalTo(100)
        }
        btmtoolView.backgroundColor = .white
        //待支付
        if orderDic.getString("orderProcessStateCode") == "待支付"  {
            btmtoolView.drawButton(button: paybtn,title: "立即支付", titleColor: .xFC4C02, fontSize: 12) { (make) in
                make.width.equalTo(110)
                make.height.equalTo(35)
                make.top.equalToSuperview().offset(10)
                make.right.equalToSuperview().offset(-10)
            }
            // 设置边框
            paybtn.layer.borderWidth = 0.5
            paybtn.layer.borderColor = UIColor.xFC4C02.cgColor
            paybtn.layer.cornerRadius = 17.5
            paybtn.addTarget(self, action: #selector(_paybtnClick(button:)), for: .touchUpInside)

//            if orderDic.getString("zoneCode") == "105001"  {
                btmtoolView.drawButton(button: cancelbtn,title: "取消订单", titleColor: .x999999, fontSize: 12) { (make) in
                    make.width.equalTo(110)
                    make.height.equalTo(35)
                    make.top.equalToSuperview().offset(10)
                    make.right.equalTo(paybtn.snp.left).offset(-10)
                }
                // 设置边框
                cancelbtn.layer.borderWidth = 0.5
                cancelbtn.layer.borderColor = UIColor.x999999.cgColor
                cancelbtn.layer.cornerRadius = 17.5
                cancelbtn.addTarget(self, action: #selector(_cancelbtnClick(button:)), for: .touchUpInside)
//            }
//            else {
//            }
            
        }
            //待发货
        else if orderDic.getString("orderProcessStateCode") == "待发货" {
//            if orderDic.getString("zoneCode") == "105001"  {
//                btmtoolView.drawButton(button: cancelbtn,title: "取消订单", titleColor: .x999999, fontSize: 12) { (make) in
//                    make.width.equalTo(110)
//                    make.height.equalTo(35)
//                    make.top.equalToSuperview().offset(10)
//                    make.right.equalToSuperview().offset(-10)
//                }
//                // 设置边框
//                cancelbtn.layer.borderWidth = 0.5
//                cancelbtn.layer.borderColor = UIColor.x999999.cgColor
//                cancelbtn.layer.cornerRadius = 17.5
//                cancelbtn.addTarget(self, action: #selector(_cancelbtnClick(button:)), for: .touchUpInside)
//            }
//            btmtoolView.isHidden = true
        }
            //待收货
        else if orderDic.getString("orderProcessStateCode") == "待收货" {
            btmtoolView.drawButton(button: signbtn,title: "确认收货", titleColor: .xFC4C02, fontSize: 12) { (make) in
                make.width.equalTo(110)
                make.height.equalTo(35)
                make.top.equalToSuperview().offset(10)
                make.right.equalToSuperview().offset(-10)
            }
            // 设置边框
            signbtn.layer.borderWidth = 0.5
            signbtn.layer.borderColor = UIColor.xFC4C02.cgColor
            signbtn.layer.cornerRadius = 17.5
            signbtn.addTarget(self, action: #selector(_signbtnClick(button:)), for: .touchUpInside)
            
            btmtoolView.drawButton(button: seebtn,title: "查看物流", titleColor: .x999999, fontSize: 12) { (make) in
                make.width.equalTo(110)
                make.height.equalTo(35)
                make.top.equalToSuperview().offset(10)
                make.right.equalTo(signbtn.snp.left).offset(-10)
            }
            // 设置边框
            seebtn.layer.borderWidth = 0.5
            seebtn.layer.borderColor = UIColor.x999999.cgColor
            seebtn.layer.cornerRadius = 17.5
            seebtn.addTarget(self, action: #selector(_seebtnClick(button:)), for: .touchUpInside)
            
        }
            //订单取消
        else if orderDic.getString("orderProcessStateCode") == "订单取消" {
            btmtoolView.isHidden = true
        }
            //已确认收货
        else if orderDic.getString("orderProcessStateCode") == "已确认收货" {
            btmtoolView.drawButton(button: seebtn,title: "查看物流", titleColor: .x999999, fontSize: 12) { (make) in
                make.width.equalTo(110)
                make.height.equalTo(35)
                make.top.equalToSuperview().offset(10)
                make.right.equalToSuperview().offset(-10)
            }
            // 设置边框
            seebtn.layer.borderWidth = 0.5
            seebtn.layer.borderColor = UIColor.x999999.cgColor
            seebtn.layer.cornerRadius = 17.5
            seebtn.addTarget(self, action: #selector(_seebtnClick(button:)), for: .touchUpInside)
        }
        
        //添加列表
        safeView.addSubview(tableView)
        tableView.backgroundColor = UIColor.clear;
        tableView.register(M_OrderCell.self, forCellReuseIdentifier: "M_OrderCell")
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.allowsMultipleSelection = true
        if orderDic.getString("orderProcessStateCode") == "订单取消" || orderDic.getString("orderProcessStateCode") == "待发货" {
            btmtoolView.isHidden = true
            tableView.snp.makeConstraints { (make) in
                make.top.equalTo(headView.snp.bottom)
                make.bottom.equalToSuperview()
                make.left.right.equalToSuperview()
            }
        }
        else {
            tableView.snp.makeConstraints { (make) in
                make.top.equalTo(headView.snp.bottom)
                make.bottom.equalTo(btmtoolView.snp.top).offset(-1)
                make.left.right.equalToSuperview()
            }
        }
    }
}

// MARK: 事件
extension M_OrderDetail {
    
    @objc func _kefuButtonClick(button: Button) {
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        let qidiandic = LocalStorage.getDic(forKey: QIDIAN_KEY)
        vc.loadUrl(qidiandic?.getString("id") ?? "https://url.cn/50hfdES?_type=wpa&qidian=true")

        vc.headTitle.text = "联系客服"
    }
    
    @objc func _paybtnClick(button: Button) {
        let vc = M_PayVC(orderDic,price: footView.priceLab.text)
        self.pushViewController(vc)
    }
    
    @objc func _cancelbtnClick(button: Button) {
        let popup = PopupConfirmBox(info: "是否取消订单？", title: "")
        popup.show(vc: UIViewController.topMostController() ?? self)
        popup.onSureButtonClick = {
            //确定执行
            self.cancelOrderAction(orderID: self.orderDic.getString("orderID") ?? "", callback: {
                self.refreshAll()
            })
        }
    }
    
    @objc func _signbtnClick(button: Button) {
        self.signOrderAction(orderID: orderDic.getString("orderID") ?? "", callback: {
            self.refreshAll()
        })
    }
    
    @objc func _seebtnClick(button: Button) {
        let vc = M_LogisticsVC(orderid: orderDic.getString("orderID") ?? "")
        self.pushViewController(vc)
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    func refreshAll() {
        for v in addressView.subviews {
            v.removeFromSuperview()
        }
        
        for v in btmtoolView.subviews {
            v.removeFromSuperview()
        }
        getorderDetail(orderID: orderDic.getString("orderID") ?? "", callback: { (data) in
            self.orderDic = data
            self.setupUI()
            self.tableView.reloadData()
        })
    }
    ///MARK: UITableViewDelegate
            // 选中cell后执行此方法
            func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                if let info = orderDic.getDictList("items")?[indexPath.row] {
                    let vc = M_ProductDetailVC(info: info)
                    self.pushViewController(vc)
                }
            }
            
            ///MARK: UITableViewDataSource
            func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                let head = UIView()
                head.backgroundColor = .clear
                head.drawView(view: addressView) { (make) in
                    make.top.equalToSuperview().offset(10)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(125.5)
                }
                addressView.backgroundColor = .white
                let img = addressView.drawImage(named: "order_status") { (make) in
                    make.top.equalToSuperview().offset(16)
                    make.left.equalToSuperview().offset(10)
                }
                addressView.drawLabel(text: orderDic.getString("orderProcessStateCode"), fontSize: 12, textColor: .x333333) { (make) in
                    make.centerY.equalTo(img)
                    make.left.equalToSuperview().offset(41.5)
                    make.right.equalToSuperview().offset(-30)
                }
                
                //画横线
                let line = addressView.drawView { (make) in
                    make.top.equalToSuperview().offset(52)
                    make.left.equalToSuperview().offset(23)
                    make.right.equalToSuperview().offset(-23)
                    make.height.equalTo(1)
                }
                line.backgroundColor = .xF2F2F2
                
                addressView.drawImage(named: "xuanzhedizhi_93") { (make) in
                    make.centerY.equalTo(line.snp.bottom).offset(26+21*0.5)
                    make.left.equalToSuperview().offset(10)
                }
                
                addressView.drawLabel(text: (orderDic.getString("receiptName") ?? "") + "  " + (orderDic.getString("mobile") ?? ""), fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
                    make.centerY.equalTo(line.snp.bottom).offset(19.5+11.5*0.5)
                    make.left.equalToSuperview().offset(41.5)
                    make.right.equalToSuperview().offset(-30)
                }
                
                addressView.drawLabel(text: orderDic.getString("receiptStreet"), fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
                    make.top.equalTo(line.snp.bottom).offset(40.5)
                    make.left.equalToSuperview().offset(41.5)
                    make.right.equalToSuperview().offset(-30)
                }
                
                
                let v = head.drawView({ (make) in
                    make.left.right.equalToSuperview()
                    make.top.equalTo(addressView.snp.bottom).offset(10)
                    make.bottom.equalToSuperview()
                })
                v.backgroundColor = .white
                
                let titlelab = head.drawLabel(text: "京东配送", fontSize: 12, textColor: .x333333) { (make) in
                    make.left.equalToSuperview().offset(30)
                    make.top.equalTo(addressView.snp.bottom).offset(30)
                }
                var imgName = "zhiyingdianpu_33"
                if orderDic.getString("zoneCode") == "105001"  {
                    titlelab.text = "自营专区"
                }
                else {
                    titlelab.text = "京东配送"
                    imgName = "jdong_34"
                }
                
                head.drawImage(named: imgName) { (make) in
                    make.right.equalTo(titlelab.snp.left).offset(-5)
                    make.centerY.equalTo(titlelab)
                }
                return head
            }
            
            //头高度
            func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
               return 195
            }
            
            //组数
            func numberOfSections(in tableView: UITableView) -> Int {
                return 1
            }
            
            //尾部高度
            func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
                return 381
            }
        
        //尾部view
        func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
            footView.orderData = orderDic
            
            return footView
        }
        
        // 设置cell高度
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 120
        }
        
            // cell的个数
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return orderDic.getDictList("items")?.count ?? 0
        }
        
            // UITableViewCell
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cellid = "M_OrderCell"
            var cell = tableView.dequeueReusableCell(withIdentifier: cellid) as? M_OrderCell
            if cell==nil {
                cell = M_OrderCell(style: .subtitle, reuseIdentifier: cellid)
            }
            
            cell?.zoonCode = orderDic.getString("zoneCode")
            cell?.unitLab.text = orderDic.getString("centUnitName")
            cell?.celldata = orderDic.getDictList("items")?[indexPath.row]
            return cell!
        }
}
